<!-- 表单组件 -->
<template>
    <div class="account-box">
        <!-- 账号登录、短信登录 -->
        <div class="toggle">
            <a @click="isMsgLogin = false" href="javascript:;" v-if="isMsgLogin">
                <i class="iconfont icon-user"></i> 使用账号登录
            </a>
            <a @click="isMsgLogin = true" href="javascript:;" v-else>
                <i class="iconfont icon-msg"></i> 使用短信登录
            </a>
        </div>
        <!-- validation-schema : 配置校验规则  v-slot：导出错误对象 -->
        <Form autocomplete="off" ref="formCom" class="form" :validation-schema="mySchema" v-slot="{ errors }">
            <!-- 使用账号登录 -->
            <template v-if="!isMsgLogin">
                <div class="form-item">
                    <div class="input">
                        <i class="iconfont icon-user"></i>
                        <Field v-model="form.account" name="account" type="text" placeholder="请输入账号" />
                    </div>
                    <div class="error" v-if="errors.account"><i class="iconfont icon-warning" />{{ errors.account }}
                    </div>
                </div>
                <div class="form-item">
                    <div class="input">
                        <i class="iconfont icon-lock"></i>
                        <Field autocomplete v-model="form.password" name="password" type="password"
                            placeholder="请输入密码" />
                    </div>
                    <div class="error" v-if="errors.password"><i class="iconfont icon-warning" />{{ errors.password }}
                    </div>
                </div>
            </template>
            <!-- 使用短信登录 -->
            <template v-else>
                <div class="form-item">
                    <div class="input">
                        <i class="iconfont icon-user"></i>
                        <!-- Field 添加name属性，作用是指定使用schema中哪个校验规则 -->
                        <Field v-model="form.mobile" name="mobile" type="text" placeholder="请输入手机号" />
                    </div>
                    <!-- Form 添加 v-slot="{errors}" 使用作用域插槽暴露 errors 错误对象
                        通过 errors['校验规则名称'] 取出错误信息，有则显示，无即隐藏 -->
                    <div class="error" v-if="errors.mobile"><i class="iconfont icon-warning" />{{ errors.mobile }}</div>
                </div>
                <div class="form-item">
                    <div class="input">
                        <i class="iconfont icon-code"></i>
                        <Field v-model="form.code" name="code" type="password" placeholder="请输入验证码" />
                        <!-- 验证码60倒计时 -->
                        <span class="code" @click="send()">{{ time === 0 ? '发送验证码' : `${time}秒后发送` }}</span>
                    </div>
                    <div class="error" v-if="errors.code"><i class="iconfont icon-warning" />{{ errors.code }}</div>
                </div>
            </template>
            <!-- 我已同意《隐私条款》... 复选框 -->
            <div class="form-item">
                <div class="agree">
                    <!-- 使用Field来渲染一个自定义的组件 而不是浏览器支持的原生标签时，需要我们添加as属性来渲染自定义组件 -->
                    <Field as="XtxCheckbox" name="isAgree" v-model="form.isAgree" @change="changeFn" />
                    <span>我已同意</span>
                    <a href="javascript:;">《隐私条款》</a>
                    <span>和</span>
                    <a href="javascript:;">《服务条款》</a>
                </div>
                <div class="error" v-if="errors.isAgree"><i class="iconfont icon-warning" />
                    {{ errors.isAgree }}
                </div>
            </div>
            <a @click="submit()" href="javascript:;" class="btn">登录</a>
        </Form>
        <!-- qq登录 忘记密码 注册 -->
        <div class="action">
            <a
                href="https://graph.qq.com/oauth2.0/authorize?client_id=100556005&response_type=token&scope=all&redirect_uri=http%3A%2F%2Fwww.corho.com%3A8080%2F%23%2Flogin%2Fcallback">
                <img src="https://qzonestyle.gtimg.cn/qzone/vas/opensns/res/img/Connect_logo_7.png" alt="">
            </a>
            <div class="url">
                <a href="javascript:;">忘记密码</a>
                <a href="javascript:;">免费注册</a>
            </div>
        </div>
    </div>
</template>
<script>
import schema from '@/utils/vee-validate-schema'
import { reactive, ref, watch, onMounted } from 'vue'
import { Form, Field } from 'vee-validate'
import { userAccountLogin, userMobileLoginMsg, userMobileLogin } from '@/api/user'
import Message from '@/components/library/Message'
import { useIntervalFn } from '@vueuse/core'
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'
export default {
    name: 'LoginForm',
    components: {
        Form, Field
    },
    setup() {
        // 是否短信登录
        const isMsgLogin = ref(false)
        // 使用v-model子元素无法改变form.isAgree，所有用另一个触发时间改变form.isAgree
        const isAgreeReplace = ref(false)
        // 使用store
        const store = useStore()
        // 使用router
        const router = useRouter()
        // 使用route
        const route = useRoute()
        // 子组件触发 改变父组件复选框状态
        const changeFn = () => {
            isAgreeReplace.value = !isAgreeReplace.value
            form.isAgree = isAgreeReplace.value
        }
        // 表单信息对象
        const form = reactive({
            isAgree: false,
            account: 'ceshi',
            password: '123456',
            mobile: '13200000000',
            code: '123456'
        })
        // 切换表单元素，还原数据和清除校验效果
        const formCom = ref(null)
        watch(isMsgLogin, () => {
            // 还原数据
            form.isAgree = false
            // 默认账号 ceshi
            form.account = 'ceshi'
            // 默认密码 123456
            form.password = '123456'
            // 默认手机号：13200000000
            form.mobile = '13200000000'
            // 默认验证码：123456
            form.code = '123456'
            // 补充校验效果清除，Form组件提供resetForm()
            // 首先需要自己手动清除数据，然后使用Form 组件提供 resetForm 方法对表单进行清除校验结果
            formCom.value.resetForm()
        })

        // 校验规则对象
        const mySchema = {
            account: schema.account,
            password: schema.password,
            mobile: schema.mobile,
            code: schema.code,
            isAgree: schema.isAgree
        }

        // 需要在点击登录的时候对整体表单进行校验
        const submit = async () => {
            // Form组件提供了一个 validate 函数作为整体表单校验，当是返回的是一个promise
            const valid = await formCom.value.validate()
            if (valid) {
                let data = null
                try {
                    // 判断是账号登录 还是短信登录
                    if (!isMsgLogin.value) {
                        data = await userAccountLogin({ ...form })
                    } else {
                        data = await userMobileLogin({ ...form })
                    }
                    // 成功
                    // 1. 存储信息
                    const { id, account, nickname, avatar, token, mobile } = data.result
                    store.commit('user/setUser', { id, account, nickname, avatar, token, mobile })
                    // 合并购物车操作
                    store.dispatch('cart/mergeLocalCart').then(() => {
                        // 2. 提示
                        Message({ type: 'success', text: '登录成功' })
                        // 3. 跳转
                        router.push(route.query.redirectUrl || '/')
                    })
                } catch (err) {
                    Message({ type: 'error', text: err.response.data.message })
                }
            }
        }
        const time = ref(0)
        // pause 暂停 resume 开始
        const { pause, resume } = useIntervalFn(() => {
            // console.log(time.value)
            time.value--
            if (time.value <= 0) {
                pause()
            }
        }, 1000, false)
        // 有一个问题 发送验证码之后销毁组件 60秒倒计时也会消失，再次点击发送验证码时，会显示验证码已经发送
        onMounted(() => {
            time.value = store.state.user.times
            if (time.value > 0) {
                resume()
            }
        })

        // 发送短信
        const send = async () => {
            // 校验手机号格式
            const valid = mySchema.mobile(form.mobile)
            if (valid === true) {
                // 通过
                if (time.value === 0) {
                    // 没有倒计时才可以发送
                    try {
                        await userMobileLoginMsg(form.mobile)
                        Message({ type: 'success', text: '发送成功' })
                        time.value = 60
                        resume()
                        store.state.user.times = 60
                        store.dispatch('user/getTime')
                    } catch (err) {
                        Message({ type: 'error', text: err.response.data.message })
                    }
                }
            } else {
                // 验证失败
            }
        }
        return { send, submit, isMsgLogin, form, mySchema, formCom, changeFn, time }
    }
}
</script>
<style lang="less" scoped>
// 账号容器
.account-box {
    .toggle {
        padding: 15px 40px;
        text-align: right;

        a {
            color: @xtxColor;

            i {
                font-size: 14px;
            }
        }
    }

    .form {
        padding: 0 40px;

        &-item {
            margin-bottom: 28px;

            .input {
                position: relative;
                height: 36px;

                >i {
                    width: 34px;
                    height: 34px;
                    background: #cfcdcd;
                    color: #fff;
                    position: absolute;
                    left: 1px;
                    top: 1px;
                    text-align: center;
                    line-height: 34px;
                    font-size: 18px;
                }

                input {
                    padding-left: 44px;
                    border: 1px solid #cfcdcd;
                    height: 36px;
                    line-height: 36px;
                    width: 100%;

                    &.error {
                        border-color: @priceColor;
                    }

                    &.active,
                    &:focus {
                        border-color: @xtxColor;
                    }
                }

                .code {
                    position: absolute;
                    right: 1px;
                    top: 1px;
                    text-align: center;
                    line-height: 34px;
                    font-size: 14px;
                    background: #f5f5f5;
                    color: #666;
                    width: 90px;
                    height: 34px;
                    cursor: pointer;
                }
            }

            >.error {
                position: absolute;
                font-size: 12px;
                line-height: 28px;
                color: @priceColor;

                i {
                    font-size: 14px;
                    margin-right: 2px;
                }
            }
        }

        .agree {
            a {
                color: #069;
            }
        }

        .btn {
            display: block;
            width: 100%;
            height: 40px;
            color: #fff;
            text-align: center;
            line-height: 40px;
            background: @xtxColor;

            &.disabled {
                background: #cfcdcd;
            }
        }
    }

    .action {
        padding: 20px 40px;
        display: flex;
        justify-content: space-between;
        align-items: center;

        .url {
            a {
                color: #999;
                margin-left: 10px;
            }
        }
    }
}
</style>